package fr.bda.cloud.storage;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import fr.bda.cloud.data.DataDescriptor;
import fr.bda.cloud.util.CloudJaxbFactory;

/**
 * This class represent a storage unit available in the cloud
 * 
 * @author BARET
 * @since 21/10/2012
 */
public class LocalStorageUnit extends StorageUnit {

	private static final FileFilter DESC_FILE_FILTER = new FileFilter() {
		@Override
		public boolean accept(File file) {
			return file.isFile() && file.getName().endsWith(EXT_DESC);
		}
	};

	/** A file directory on the file system */
	File localDirectory;

	public LocalStorageUnit(LocalStorageUnitConfiguration localStorageUnitConfiguration) {
		this.localDirectory = localStorageUnitConfiguration.getLocalFolder();
	}

	public LocalStorageUnit(File localDirectory) {
		this.localDirectory = localDirectory;
	}

	@Override
	public List<DataDescriptor> listData() {
		List<DataDescriptor> res = new ArrayList<>();
		for (File f : localDirectory.listFiles(DESC_FILE_FILTER)) {
			res.add(CloudJaxbFactory.unmarshal(f, DataDescriptor.class));
		}
		return res;
	}

	@Override
	public byte[] readData(DataDescriptor dataDescriptor) {
		byte[] res = new byte[dataDescriptor.getDataSize().intValue()];
		File binFile = new File(localDirectory, dataDescriptor.getFileName() + EXT_DATA);
		try (FileInputStream binFis = new FileInputStream(binFile);) {
			binFis.read(res);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}

	@Override
	public void saveData(DataDescriptor dataDescriptor, byte[] data) {
		File binFile = new File(localDirectory, dataDescriptor.getFileName() + EXT_DATA);
		File descFile = new File(localDirectory, dataDescriptor.getFileName() + EXT_DESC);
		try (FileOutputStream binFos = new FileOutputStream(binFile);) {

			// Write the bin file
			binFos.write(data);

			// Write the descriptor file
			CloudJaxbFactory.marshal(dataDescriptor, descFile);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void clearData(DataDescriptor dataDescriptor) {
		File binFile = new File(localDirectory, dataDescriptor.getFileName() + EXT_DATA);
		File descFile = new File(localDirectory, dataDescriptor.getFileName() + EXT_DESC);
		descFile.delete();
		binFile.delete();
	}

}
